package com.jy.rhin.config.ws;

import lombok.extern.slf4j.Slf4j;
import org.apache.cxf.interceptor.Interceptor;
import org.apache.cxf.message.Message;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: ws工厂
 * @Author: lww
 * @Date: 2022/5/18
 */
@Slf4j
public abstract class BaseWsFactory implements ApplicationContextAware {

    protected ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    protected List<Interceptor<? extends Message>> matchInterceptor(Collection<InterceptorProperties> inInterceptors, String wsUrl) {
        List<Class<Interceptor<? extends Message>>> collect = inInterceptors.stream()
                .filter(interceptorProperties -> {
                    String url = interceptorProperties.getUrl();
                    return StringUtils.isEmpty(url) || matchPath(Arrays.asList(url.split(",")), wsUrl);
                })
                .map(InterceptorProperties::getClazz)
                .collect(Collectors.toList());
        ArrayList<Interceptor<? extends Message>> interceptors = new ArrayList<>();
        for (Class<Interceptor<? extends Message>> interceptorClass : collect) {
            Interceptor<? extends Message> bean = applicationContext.getBean(interceptorClass);
            interceptors.add(bean);
        }
        return interceptors;
    }

    private boolean matchPath(List<String> url, String wsUrl) {
        boolean flag = false;
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        for (String pattern : url) {
            if (antPathMatcher.match(pattern, wsUrl)) {
                flag = true;
                break;
            }
        }
        log.info("计算匹配路径 {} ==> {}, 结果={}", wsUrl, url, flag);
        return flag;
    }

}
